package com.netty.handler;

import java.io.UnsupportedEncodingException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netty.util.MessageBody;
import com.netty.util.MessageHeader;
import com.netty.util.NettyMessage;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

public class ServerMessageHandler extends ChannelInboundHandlerAdapter  {

	//IP白名单
	public static final String[] ips = {"127.0.0.0"};
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("接收到客户端创建的连接 from:"+ctx.name());
	}
	
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
    	HttpRequest request = null;
        if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;
            String uri = request.uri();
            System.out.println("Uri:" + uri);
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            String requestMessage = buf.toString(CharsetUtil.UTF_8);
            NettyMessage nettyMessage = JSONObject.parseObject(requestMessage, NettyMessage.class);
            buf.release();
            MessageHeader header = nettyMessage.getHeader();
            MessageBody body = nettyMessage.getBody();
            int type = header.getType();
            if(type == 0){
        		JSONObject json = new JSONObject();
        		json.put("code", 200);
        		json.put("matched", "true");
        		String messageBody = json.toJSONString();
	    		this.response(ctx, messageBody);
            }else if(type == 5){
            	String crcCode = header.getCrcCode();
            	String ip = body.getIp();
            	boolean flag = false;
            	for(int i = 0, j = ips.length;i<j;i++){
            		if(ips[i].equals(ip) && "chenmutime".equals(crcCode)){
            			flag = true;
            			break;
            		}
            	}
            	if(flag){
            		JSONObject json = new JSONObject();
            		json.put("code", 200);
            		json.put("reason", "correct request");
            		String messageBody = json.toJSONString();
    	    		this.response(ctx, messageBody);
            	}else {
            		JSONObject json = new JSONObject();
            		json.put("code", 401);
            		json.put("reason", "illegal request");
            		String messageBody = json.toJSONString();
    	    		this.response(ctx, messageBody);
    	    		ctx.close();
				}
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    private void response(ChannelHandlerContext ctx, String messageBody) throws UnsupportedEncodingException{
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(messageBody.getBytes("UTF-8")));
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.writeAndFlush(response);
    }
}
